
import 'package:fate_blind_box/im/groupchat.dart';
import 'package:fate_blind_box/im/person_info.dart';
import 'package:fate_blind_box/network/Api.dart';
import 'package:fate_blind_box/routes/page_route_names.dart';
import 'package:fate_blind_box/theme/theme_color.dart';
import 'package:fate_blind_box/utils/provider.dart';
import 'package:fate_blind_box/widget/icon_text.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:im_flutter_sdk/im_flutter_sdk.dart';
import '../../../utils/loading.dart';

//通讯录首页
class memManagerUi extends StatefulWidget {
  const memManagerUi({Key? key}) : super(key: key);

  @override
  State<memManagerUi> createState() => _memManagerUiState();
}

class _memManagerUiState extends State<memManagerUi>
    with SingleTickerProviderStateMixin, WidgetsBindingObserver {
  List addmessage = [];
  final ScrollController _scrollController = ScrollController(); //listview的控制器
  int _page = 1; //加载的页数
  bool isLoading = false; //是否正在加载数据
  int _index = 0;
  List<String> lists=[];

  final List _listData = [];
  int _pageNum = 1;

  late double _screenWidth;

  _onTabChanged() {
    gettype(_index);
    _listData == [];
    _listData.clear();
    _getListData(_page, _index);
    setState(() {});
  }

  /// 上拉加载更多
  Future _getMore() async {
    if (!isLoading) {
      setState(() {
        isLoading = true;
      });
      await Future.delayed(const Duration(seconds: 1), () {});
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    initdata();
    _getListData(_page, 0);
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        _getMore();
      }
    });

    setState(() {});
  }

  void initdata() async {

    lists = await EMClient.getInstance.contactManager.getAllContactsFromServer();
    if (lists.isNotEmpty) {

      //保存好友信息
      setMessagelist(lists, '2');
    }
    setState(() {});
  }

  @override
  void dispose() {
    super.dispose();
    //3. 页面销毁时，移出监听者
    // WidgetsBinding.instance?.removeObserver(this);
  }

  //一些状态改变监听方法

  //监听程序进入前后台的状态改变的方法
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    // TODO: implement didChangeAppLifecycleState
    super.didChangeAppLifecycleState(state);

    switch (state) {
    //进入应用时候不会触发该状态 应用程序处于可见状态，并且可以响应用户的输入事件。它相当于 Android 中Activity的onResume
      case AppLifecycleState.resumed:
        print("应用进入前台======");
        break;
    //应用状态处于闲置状态，并且没有用户的输入事件，
    // 注意：这个状态切换到 前后台 会触发，所以流程应该是先冻结窗口，然后停止UI
      case AppLifecycleState.inactive:
        print("应用处于闲置状态，这种状态的应用应该假设他们可能在任何时候暂停 切换到后台会触发======");
        break;
    //当前页面即将退出
      case AppLifecycleState.detached:
        print("当前页面即将退出======");
        break;
    // 应用程序处于不可见状态
      case AppLifecycleState.paused:
        print("应用处于不可见状态 后台======");
        break;
    }
  }

  /// 下拉刷新方法,为list重新赋值
  Future<void> _onRefresh() async {
    await Future.delayed(const Duration(seconds: 3), () {});
  }

  /// 加载更多时显示的组件,给用户提示
  Widget _getMoreWidget() {
    return Center(
      child: Offstage(
        offstage: !isLoading,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: const <Widget>[
            Text(
              '加载中...',
              style: TextStyle(fontSize: 16.0),
            ),
            CircularProgressIndicator(
              strokeWidth: 1.0,
            )
          ],
        ),
      ),
    );
  }

  Widget gettype(int index) {
    return SizedBox(
      height: 500,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Center(
            child: Image.asset(
              'images/ic_nofriend.png',
              width: 175,
              height: 122,
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    _screenWidth = MediaQuery.of(context).size.width;
    return Scaffold(
      appBar: AppBar(
        iconTheme: const IconThemeData(color: Colors.black),
        title: Text(
          "会员管理",
          style: TextStyle(
              fontSize: 18,
              color: ThemeColor.textColor,
              fontWeight: FontWeight.bold),
        ),
        centerTitle: true,
        elevation: 0,
        backgroundColor: Colors.white,
        systemOverlayStyle: SystemUiOverlayStyle.light,
      ),
      backgroundColor: Colors.white,
      body: Column(
        children: [
          _buildSearchBar(),
          Expanded(
            flex: 1,
            child:RefreshIndicator(
              onRefresh: _onRefresh,
              child: _listData.isNotEmpty
                  ? ListView.builder(
                  controller: _scrollController,
                  padding: const EdgeInsets.all(8.0),
                  itemCount: _listData.length,
                  itemBuilder: (BuildContext context, int index) {
                    if (index == _listData.length) {
                      //加载更多
                      return _getMoreWidget();
                    } else {
                      if (_listData?.isNotEmpty == true) {
                        return _buildItems(
                            _listData?[index], index);
                      } else {
                        return Container();
                      }
                    }
                  }) : gettype(_index),
            ),

          ),
          // Expanded(child: _buildListView())
        ],
      ),
    );
  }

  /// 获取列表数据
  _getListData(
      int page,
      int index,
      ) async {

    switch (index) {
      case 0:
      //好友
        final easeName = await Provider.getUserEaseName();
        if (easeName.isEmpty) return;
        final res = await Api.getInstance().getFanLists(Provider.userEaseName);
        final data = res['data'];
        if (data != null) {
          List list = data;
          if (list.isNotEmpty) {
            _listData.clear();
            setState(() {
              _listData.addAll(list);
            });
          }
          //获取好友列表成功后调用群列表后台加缓存
          await Api.getInstance().getGroupList(Provider.userEaseName);
        } else {
        }

        break;
    }
  }

  void setMessagelist(List addmessage, String type) async {
    if (Provider.userEaseName.isEmpty || addmessage.isEmpty) return;
    //--类型 （1：消息，2：好友，3：粉丝，4：群聊， 5：新朋友）
    final res = await Api.getInstance()
        .addMessagelist(Provider.userEaseName, addmessage, type);

    if (res['code'] == 0) {
    } else {
      toast(res['msg']);
    }
  }

  //删除好友
  void deleteuser(String string, int index) async {
    final res = await Api.getInstance().deleteUsers(string);

    if (res['code'] == 0) {
      setState(() {
        _listData.removeAt(index);
      });
    } else {
      if (kDebugMode) {
        print('------通讯录异常记录---------------' + res['msg']);
      }
    }
  }

  Widget _buildSearchBar() {
    return GestureDetector(
      onTap: () {},
      child: Container(
          height: 36,
          margin: const EdgeInsets.symmetric(horizontal: 12),
          padding: const EdgeInsets.symmetric(horizontal: 24),
          decoration: ShapeDecoration(
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(18)),
              color: const Color(0xFFF7F7F7)),
          alignment: Alignment.centerLeft,
          child: IconText(
            "  搜索",
            style: TextStyle(color: ThemeColor.textColorSecond, fontSize: 14),
            icon: const Icon(
              Icons.search_rounded,
              size: 17,
              color: Color(0xFFBABABA),
            ),
            beforeText: true,
          )),
    );
  }

  Widget _buildFoldingItem(int index, String name, int count) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 12),
      height: 52,
      decoration: BoxDecoration(
          border: Border(
              bottom: BorderSide(color: ThemeColor.dividerColor, width: 1))),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Text(
            name,
            style: TextStyle(color: ThemeColor.textColor, fontSize: 15),
          ),
          Text(
            "$count",
            style: TextStyle(color: ThemeColor.textColorSecond, fontSize: 14),
          )
        ],
      ),
    );
  }

  _buildItems(Map map ,int index) {
    switch (_index) {
      case 0:

        return GestureDetector(
          onTap: () {
            if (map['id'].toString().isEmpty) return;
            Get.to(PersonInfo(sig: map['id'].toString()),
                routeName: PageRouteNames.personInfoPage);
          },
          child: _listData.isNotEmpty
              ? Container(
            height: 70,
            margin: const EdgeInsets.symmetric(horizontal: 12,),
            decoration: BoxDecoration(
              border: Border(
                  bottom: BorderSide(
                      color: ThemeColor.dividerColor, width: 1)),
            ),

            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Stack(

                  children: [
                    ClipRRect(
                      borderRadius: const BorderRadius.only(
                          topLeft: Radius.circular(6),
                          topRight: Radius.circular(6),
                          bottomLeft: Radius.circular(6)
                      ),
                      child: Image.network(
                          map['profilePhoto'],
                          width: 50,
                          height: 50,
                          fit: BoxFit.cover
                      ),
                    ),
                  ],
                ),

                const SizedBox(
                  width: 12,
                ),
                Expanded(
                  child: Container(
                    padding: const EdgeInsets.symmetric(vertical: 5),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        SizedBox(
                          width: 200,
                          child: Text(
                            map["nickName"] ?? "",
                            style: TextStyle(
                                color: ThemeColor.textColor,
                                fontSize: 15,
                                fontWeight: FontWeight.w600),
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: [
                            Container(
                              margin: const EdgeInsets.only(right: 8),
                              padding: const EdgeInsets.only(
                                  left: 8, right: 8, top: 1, bottom: 1),
                              alignment: Alignment.center,
                              decoration: ShapeDecoration(
                                  shape: RoundedRectangleBorder(
                                    borderRadius:
                                    BorderRadius.circular(36),
                                  ),
                                  color: map['realSex'] == 2
                                      ? ThemeColor.mainColor
                                      : Colors.blue),
                              child: IconText(
                                map['age'].toString() == 'null' ? ' 0' : ' ${map['age'].toString()}',
                                icon: Icon(
                                    map['realSex'] == 2
                                        ? Icons.female
                                        : Icons.male,
                                    color: Colors.white),
                                iconSize: 12,
                                style: const TextStyle(
                                  color: Colors.white,
                                  fontSize: 12,
                                ),
                              ),
                            ),
                            Image.asset(
                              "images/ic_path.png",
                              width: 11,
                              height: 13,
                            ),
                            const SizedBox(width: 3,),
                            SizedBox(
                              width: 90,
                              child:
                              Text(
                                map["homeAddr"] ?? "",
                                style: TextStyle(
                                    color: ThemeColor.textColorSecond,
                                    fontSize: 12,
                                    overflow: TextOverflow.ellipsis
                                ),
                              ),
                            )
                          ],
                        ),
                      ],
                    ),
                  ),
                ),

              ],
            ),
          )
              : SizedBox(
            height: 500,
            width: 500,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Center(
                  child: Image.asset(
                    'images/ic_nofriend.png',
                    width: 175,
                    height: 122,
                  ),
                ),
              ],
            ),
          ),
        );

        break;
    }
  }

  _showCustomModalBottomSheet(context, List<String> options) async {
    return showModalBottomSheet<int>(
      backgroundColor: Colors.transparent,
      isScrollControlled: true,
      context: context,
      builder: (BuildContext context) {
        return Container(
          clipBehavior: Clip.antiAlias,
          decoration: const BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(20.0),
              topRight: Radius.circular(20.0),
            ),
          ),
          child: Column(children: [
            SizedBox(
              height: 50,
              child: Stack(
                textDirection: TextDirection.rtl,
                children: [
                  const Center(
                    child: Text(
                      '底部弹窗',
                      style: TextStyle(
                          fontWeight: FontWeight.bold, fontSize: 16.0),
                    ),
                  ),
                  IconButton(
                      icon: const Icon(Icons.close),
                      onPressed: () {
                        Navigator.of(context).pop();
                      }),
                ],
              ),
            ),
            const Divider(height: 1.0),
            Expanded(
              child: ListView.builder(
                itemBuilder: (BuildContext context, int index) {
                  return ListTile(
                      title: Text(options[index]),
                      onTap: () {
                        Navigator.of(context).pop(index);
                      });
                },
                itemCount: options.length,
              ),
            ),
          ]),
        );
      },
    );
  }
}
